##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import urllib.request as url
from ast import literal_eval

try:
    from lxml import etree
except ImportError:
    import xml.etree.ElementTree as etree


class InvalidTag(Exception):
    pass


class XmlReader:

    tag = {
           'medialist': 0,
           'program': 1,
           'plugins': 2
           }

    def __init__(self, file):
        parser = etree.XMLParser(remove_blank_text=True)
        self.root = etree.parse(file, parser).getroot()

    def readMedia(self, media):
        conf = {}
        uuid = ''
        for opt in media:
            if(opt.attrib['name'] == 'uuid'):
                uuid = url.url2pathname(opt.attrib['value'])
            else:
                conf[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return (uuid, conf)

    def readMediaList(self):
        medialist = []
        for media in self.root[self.tag['medialist']]:
            medialist.append(self.readMedia(media))
        return medialist

    def readPluginSettings(self, plugin):
        conf = {}
        for opt in plugin:
            conf[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return conf

    def readPluginsSettings(self):
        plugins = {}
        for plugin in self.root[self.tag['plugins']]:
            plug = plugin.attrib['name']
            plugins[plug] = self.readPluginSettings(plugin)
        return plugins

    def readProgramSettings(self):
        settings = {}
        for opt in self.root[self.tag['program']]:
            settings[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return settings
